package com.adee.util;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;

public class DesUtil {
    //
    public static void main(String args[]) {
        String str = "yui763efgj74wscho871qzxcr68";
        String password = "1qaz@WSX11";
        byte[] result = DesUtil.encrypt(str.getBytes(StandardCharsets.UTF_8),password);
        System.out.println("origin:");
        Util.printByteArr(str.getBytes(StandardCharsets.UTF_8));
        System.out.println("encrypt:");
        Util.printByteArr(result);
        try {
            byte[] decryResult = DesUtil.decrypt(result, password);
            System.out.println("decrypt:");
            Util.printByteArr(decryResult);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public static  byte[] encrypt(byte[] datasource, String password) {
        try{
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes(StandardCharsets.UTF_8));
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secureKey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, secureKey, random);
            return cipher.doFinal(datasource);
        }catch(Throwable e){
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] decrypt(byte[] src, String password) throws Exception {
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes(StandardCharsets.UTF_8));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secureKey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, secureKey, random);
        return cipher.doFinal(src);
    }
}
